package com.atguigu.sparsearray;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ChessTest {
    public static void main(String[] args) {
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;// 1表示黑子，2表示白子
        chessArr1[2][3] = 2;
        chessArr1[6][4] = 2;
        System.out.println("原始二维数组");
        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        // 二维转稀疏数组
        int sum = 0;
        for (int[] row : chessArr1) {
            for (int data : row) {
                if (data != 0) {
                    sum++;
                }
            }
        }
        int [][] sparseArr = new int[sum+1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        int count = 0;// 用来记录是第几个非0数据
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                }
            }
        }
        // 输出稀疏数组
        System.out.println("稀疏数组为");
        for (int[] row : sparseArr)
            System.out.printf("%d\t%d\t%d\n", row[0], row[1], row[2]);
        // 将稀疏数组保存到当前包下的chess.txt文件中
        // SavaSparseArrayToFile.SavaSparseArrayToFile(sparseArr, "D:\\code\\DataStructure\\day01\\src\\com\\atguigu\\sparsearray\\chess.txt");


        System.out.println("恢复后的二维数组");
        int [][] loadSparseArr = LoadSparseArrayFromFile.loadSparseArrayFromFile("D:\\code\\DataStructure\\day01\\src\\com\\atguigu\\sparsearray\\chess.txt");
        assert loadSparseArr != null;
        int [][] chessArr2 = new int[loadSparseArr[0][0]][loadSparseArr[0][1]];
        for (int i = 1; i < loadSparseArr.length; i++){
            chessArr2[loadSparseArr[i][0]][loadSparseArr[i][1]] = loadSparseArr[i][2];
        }
        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}
